package com.moto.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.moto.bean.AddFriendPostsBean;
import com.moto.bean.AddPicPostsBean;
import com.moto.bean.AddTradePostsBean;
import com.moto.bean.Bean;
import com.moto.bean.Desc;
import com.moto.bean.ImageFileBean;
import com.moto.bean.ImageInfoBean;
import com.moto.bean.ImageUrlBean;
import com.moto.bean.Pic;
import com.moto.bean.PostsFriendBean;
import com.moto.bean.PostsTradeBean;
import com.moto.bean.Size;
import com.moto.common.PostType;
import com.moto.entity.Posts;
import com.moto.entity.PostsFriend;
import com.moto.entity.PostsTrade;
import com.moto.service.MotoUserService;
import com.moto.service.PostsCommentService;
import com.moto.service.PostsFriendApplyService;
import com.moto.service.PostsFriendService;
import com.moto.service.PostsService;
import com.moto.service.PostsTradeService;
import com.moto.service.UserRemindService;
import com.moto.service.UserRepliesService;
import com.moto.service.UserStoreService;
import com.moto.service.UserSubjectService;
import com.moto.util.CreateID;
import com.moto.util.DateUtils;
import com.moto.util.QiNiuFileUpload;

@Scope("prototype")
@RequestMapping("/posts")
@Controller
public class PostsController {

	private static final Logger LOG = Logger.getLogger(PostsController.class);

	@Autowired
	private PostsService postsService;
	@Autowired
	private PostsFriendService postsFriendService;
	@Autowired
	private PostsTradeService postsTradeService;
	@Autowired
	private PostsFriendApplyService postsFriendApplyService;
	@Autowired
	private PostsCommentService postsCommentService;
	@Autowired
	private UserRemindService userRemindService;
	@Autowired
	private UserRepliesService userRepliesService;
	@Autowired
	private UserStoreService userStoreService;
	@Autowired
	private UserSubjectService userSubjectService;
	@Autowired
	private MotoUserService motoUserService;

	private static final String NULL = "";

	/**
	 * 帖子加精
	 * 
	 * @param postsId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addDigest", method = RequestMethod.GET)
	public String addDigest(@RequestParam("postsId") String postsId) {
		LOG.debug("帖子加精，postsId = " + postsId);
		boolean addDigest = postsService.addDigest(postsId);
		if (addDigest) {
			return Boolean.TRUE.toString();
		} else {
			return Boolean.FALSE.toString();
		}
	}

	/**
	 * 帖子去精
	 * 
	 * @param postsId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteDigest", method = RequestMethod.GET)
	public String deleteDigest(@RequestParam("postsId") String postsId) {
		LOG.debug("帖子去精，postsId = " + postsId);
		boolean addDigest = postsService.deleteDegest(postsId);
		if (addDigest) {
			return Boolean.TRUE.toString();
		} else {
			return Boolean.FALSE.toString();
		}
	}

	/**
	 * 组队贴列表分页查询
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @param postsType
	 * @return
	 */
	@RequestMapping(value = "/getPostsFriendByPage", method = RequestMethod.GET)
	public String teamPostsList(Model model, @RequestParam("pageNum") int pageNum,
			@RequestParam("pageSize") int pageSize) {
		LOG.info("组队贴分页查询");
		PageHelper.startPage(pageNum, pageSize);
		List<PostsFriendBean> list = postsService.getTeamPostsList();
		PageInfo<PostsFriendBean> pageInfo = new PageInfo<PostsFriendBean>(list);
		model.addAttribute("page", pageInfo);
		return "postsFriend";
	}

	/**
	 * 组队贴列表查询，不分页
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @param postsType
	 * @return
	 */
	@RequestMapping(value = "/getPostsFriend", method = RequestMethod.GET)
	public String teamPostsList(Model model) {
		LOG.info("组队贴分页查询");
		List<PostsFriendBean> postsFriend = postsService.getTeamPostsList();
		model.addAttribute("postsFriend", postsFriend);
		return "post_team_manager";
	}

	/**
	 * 交易贴列表分页查询
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @param postsType
	 * @return
	 */
	@RequestMapping(value = "/getPostsTradeByPage", method = RequestMethod.GET)
	public String tradePostsList(Model model, @RequestParam("pageNum") int pageNum,
			@RequestParam("pageSize") int pageSize) {
		LOG.debug("分页查询交易贴");
		PageHelper.startPage(pageNum, pageSize);
		List<PostsTradeBean> list = postsService.getTradePostsList();
		PageInfo<PostsTradeBean> pageInfo = new PageInfo<PostsTradeBean>(list);
		model.addAttribute("page", pageInfo);
		return "postsTrade";
	}

	/**
	 * 交易贴列表查询，不分页
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @param postsType
	 * @return
	 */
	@RequestMapping(value = "/getPostsTrade", method = RequestMethod.GET)
	public String tradePostsList(Model model) {
		LOG.debug("分页查询交易贴");
		List<PostsTradeBean> postsTrade = postsService.getTradePostsList();
		model.addAttribute("postsTrade", postsTrade);
		return "post_trade_manager";
	}


	/**
	 * 图文贴列表分页查询
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/getPostsPicByPage", method = RequestMethod.GET)
	public String picPostsList(Model model, @RequestParam("pageNum") int pageNum,
			@RequestParam("pageSize") int pageSize) {
		LOG.debug("图文贴列表分页查询");
		PageHelper.startPage(pageNum, pageSize);
		List<Posts> list = postsService.getPicPosts();
		PageInfo<Posts> pageInfo = new PageInfo<Posts>(list);
		model.addAttribute("page", pageInfo);
		return "postsPic";
	}

	/**
	 * 图文贴列表查询，不分页
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/getPostsPic", method = RequestMethod.GET)
	public String picPostsList(Model model) {
		LOG.debug("图文贴列表分页查询");
		List<Posts> postsPic = postsService.getPicPosts();
		model.addAttribute("postsPic", postsPic);
		return "post_picture_manager";
	}

	/**
	 * 发现贴分页查询
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/getPostsDiscoverByPage", method = RequestMethod.GET)
	public String discoverPostsList(Model model, @RequestParam("pageNum") int pageNum,
			@RequestParam("pageSize") int pageSize) {
		LOG.debug("图文贴列表分页查询");
		PageHelper.startPage(pageNum, pageSize);
		List<Posts> list = postsService.getDiscoverPosts();
		PageInfo<Posts> pageInfo = new PageInfo<Posts>(list);
		model.addAttribute("page", pageInfo);
		return "postsPic";
	}

	/**
	 * 发现贴查询，查询所有，不分页
	 * 
	 * @param model
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/getAllPostsDiscover", method = RequestMethod.GET)
	public String discoverPostsList(Model model) {
		LOG.debug("发现贴列表分页查询");
		List<Posts> discoverPosts = postsService.getDiscoverPosts();
		model.addAttribute("discoverPosts", discoverPosts);
		return "post_find_manager";
	}

	/**
	 * 发现贴,图文贴发布
	 * 
	 * @param addPostsBean
	 * @param post_pic
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addPicPosts", method = RequestMethod.POST)
	public String addPosts(AddPicPostsBean addPostsBean, @RequestParam MultipartFile[] post_pic,
			@RequestParam List<String> picdesc, HttpServletRequest request) {

		String postsId = CreateID.generate();
		/**
		 * 图片上传
		 */
		Map<String, String> parceImageInfo = null;
		if(post_pic.length>0){
			List<ImageFileBean> imageList = uploadFiles(post_pic, postsId);
			parceImageInfo = parceImageInfo(imageList);
		}


		Posts posts = new Posts();
		posts.setPostsArea("1");
		posts.setPostsComment(0l);
		posts.setPostsContent(addPostsBean.getContent());
		posts.setPostsCreatetime(DateUtils.dateToUnixTimestamp());
		posts.setPostsUpdateTime(DateUtils.dateToUnixTimestamp());
		posts.setPostsId(postsId);
		posts.setPostsLike(0l);
		if(null != parceImageInfo){
			posts.setPostsPics(parceImageInfo.get("url"));
			posts.setPostsPicsSize(parceImageInfo.get("size"));
		
			Desc[] descArray = new Desc[picdesc.size()];
			for (int i = 0; i < picdesc.size(); i++) {
				Desc desc = new Desc();
				desc.setDesc(picdesc.get(i));
				descArray[i] = desc;
			}
	
			GsonBuilder gsonBuilder = new GsonBuilder();
			Gson gson = gsonBuilder.create();
			posts.setPostsPicsDesc(gson.toJson(descArray));
		}
		posts.setPostsRead(0l);
		posts.setPostsSubject(addPostsBean.getSubject());
		switch (addPostsBean.getPostsType()) {
			case 1:
				posts.setPostsType(PostType.POST_TYPE_PIC);
				break;
			case 4:
				posts.setPostsType(PostType.POST_TYPE_DISCOVER);
				break;
		}
		posts.setPostUserId("15454d21023112m");

		int insert = postsService.insert(posts);
		if (insert > 0) {
			LOG.debug("发现贴  发帖成功");
		}

		String returnString = "";
		switch (addPostsBean.getPostsType()) {
			case 1:
				returnString = "redirect:/posts/getPostsPic";
				break;
			case 4:
				returnString = "redirect:/posts/getAllPostsDiscover";
				break;
		}

		return returnString;
	}

	/**
	 * 发现贴,图文贴修改
	 * 
	 * @param addPostsBean
	 * @param post_pic
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updatePosts", method = RequestMethod.POST)
	public String updatePosts(AddPicPostsBean addPostsBean, String postsId,
			@RequestParam MultipartFile[] post_pic, @RequestParam List<String> picdesc,
			HttpServletRequest request) {

		/**
		 * 图片上传
		 */
		Map<String, String> parceImageInfo = null;
		if (post_pic.length > 0) {
			List<ImageFileBean> imageList = uploadFiles(post_pic, postsId);
			parceImageInfo = parceImageInfo(imageList);
		}

		Posts posts = postsService.getPostsById(postsId);
		posts.setPostsContent(addPostsBean.getContent());
		posts.setPostsUpdateTime(DateUtils.dateToUnixTimestamp());
		if (post_pic.length > 0) {
			GsonBuilder gsonBuilder = new GsonBuilder();
			Gson gson = gsonBuilder.create();

			String[] pic = gson.fromJson(posts.getPostsPics(), Pic.class).getPic();
			String[] newPic = gson.fromJson(parceImageInfo.get("url"), Pic.class).getPic();
			Pic picbean = new Pic();
			picbean.setPic(ArrayUtils.addAll(pic, newPic));
			posts.setPostsPics(gson.toJson(picbean));

			Size[] picSize = gson.fromJson(posts.getPostsPicsSize(), Size[].class);
			Size[] sizeJson = gson.fromJson(parceImageInfo.get("size"), Size[].class);
			Size[] addAll = ArrayUtils.addAll(picSize, sizeJson);
			posts.setPostsPicsSize(gson.toJson(addAll));

			String postsPicsDesc = posts.getPostsPicsDesc();
			int length = pic.length;
			Desc[] picDesc = null;
			if (null == postsPicsDesc || postsPicsDesc.equals("")) {
				picDesc = new Desc[length];
				for (int i = 0; i < length; i++) {
					Desc desc = new Desc();
					desc.setDesc("");
					picDesc[i] = desc;
				}
			} else {
				picDesc = gson.fromJson(postsPicsDesc, Desc[].class);
			}
			Desc[] newDesc = new Desc[picdesc.size()];
			for (int i = 0; i < picdesc.size(); i++) {
				Desc desc = new Desc();
				desc.setDesc(picdesc.get(i));
				newDesc[i] = desc;
			}
			Desc[] all = ArrayUtils.addAll(picDesc, newDesc);
			posts.setPostsPicsDesc(gson.toJson(all));
		}
		posts.setPostsSubject(addPostsBean.getSubject());
		switch (addPostsBean.getPostsType()) {
			case 1:
				posts.setPostsType(PostType.POST_TYPE_PIC);
				break;
			case 4:
				posts.setPostsType(PostType.POST_TYPE_DISCOVER);
				break;
		}
		posts.setPostUserId("15454d21023112m");

		int update = postsService.updateByPrimaryKeySelective(posts);
		if (update > 0) {
			LOG.debug("发现贴  更新成功");
		}

		String returnString = "";
		switch (addPostsBean.getPostsType()) {
			case 1:
				returnString = "redirect:/posts/getPostsPic";
				break;
			case 4:
				returnString = "redirect:/posts/getAllPostsDiscover";
				break;
		}

		return returnString;
	}



	/**
	 * 发布组队贴
	 * 
	 * @param addFriendPostsBean
	 *        组队贴页面封装对象
	 * @param post_pic
	 *        图片
	 * @param picdesc
	 *        图片描述List
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addFriendPosts", method = RequestMethod.POST)
	public String addFriendPosts(AddFriendPostsBean addFriendPostsBean,
			@RequestParam MultipartFile[] post_pic, @RequestParam List<String> picdesc,
			HttpServletRequest request) {

		String postsId = CreateID.generate();

		/**
		 * 图片上传
		 */
		Map<String, String> parceImageInfo = null;
		if(post_pic.length>0){
			List<ImageFileBean> imageList = uploadFiles(post_pic, postsId);
			parceImageInfo = parceImageInfo(imageList);
		}
		Posts posts = new Posts();
		posts.setPostsArea(addFriendPostsBean.getPostsArea());
		posts.setPostsComment(0l);
		posts.setPostsContent(addFriendPostsBean.getPostsContent());
		posts.setPostsCreatetime(DateUtils.dateToUnixTimestamp());
		posts.setPostsUpdateTime(DateUtils.dateToUnixTimestamp());
		posts.setPostsId(postsId);
		posts.setPostsLike(0l);
		if(null != parceImageInfo){
			posts.setPostsPics(parceImageInfo.get("url"));
			posts.setPostsPicsSize(parceImageInfo.get("size"));
		
			Desc[] descArray = new Desc[picdesc.size()];
			for (int i = 0; i < picdesc.size(); i++) {
				Desc desc = new Desc();
				desc.setDesc(picdesc.get(i));
				descArray[i] = desc;
			}
	
			GsonBuilder gsonBuilder = new GsonBuilder();
			Gson gson = gsonBuilder.create();
			posts.setPostsPicsDesc(gson.toJson(descArray));
		}
		posts.setPostsRead(0l);
		posts.setPostsSubject(addFriendPostsBean.getPostsSubject());
		posts.setPostUserId("15454d21023112m");
		posts.setPostsType(PostType.POST_TYPE_FRIEND);
		int insert = postsService.insert(posts);
		if (insert > 0) {
			PostsFriend friend = new PostsFriend();
			friend.setPId(CreateID.generate());
			friend.setPostsAssembleTime(addFriendPostsBean.getPostsAssembleTime());
			friend.setPostsDestination(addFriendPostsBean.getPostsDestination());
			friend.setPostsId(postsId);
			friend.setPostsPhone(addFriendPostsBean.getPostsPhone());
			friend.setPostsPopulation(addFriendPostsBean.getPostsPopulation());
			friend.setPostsRendezvous(addFriendPostsBean.getPostsRendezvous());
			postsFriendService.insert(friend);
		}
		return "redirect:/posts/getPostsFriend";
	}

	/**
	 * 更新组队贴
	 * 
	 * @param addFriendPostsBean
	 *        组队贴页面封装对象
	 * @param post_pic
	 *        图片
	 * @param picdesc
	 *        图片描述List
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateFriendPosts", method = RequestMethod.POST)
	public String updateFriendPosts(AddFriendPostsBean addFriendPostsBean, String postsId,
			@RequestParam MultipartFile[] post_pic, @RequestParam List<String> picdesc,
			HttpServletRequest request) {

		/**
		 * 图片上传
		 */
		Map<String, String> parceImageInfo = null;
		if (post_pic.length > 0) {
			List<ImageFileBean> imageList = uploadFiles(post_pic, postsId);
			parceImageInfo = parceImageInfo(imageList);
		}
		Posts posts = postsService.getPostsById(postsId);
		posts.setPostsContent(addFriendPostsBean.getPostsContent());
		posts.setPostsUpdateTime(DateUtils.dateToUnixTimestamp());
		if (post_pic.length > 0) {
			GsonBuilder gsonBuilder = new GsonBuilder();
			Gson gson = gsonBuilder.create();

			String[] pic = gson.fromJson(posts.getPostsPics(), Pic.class).getPic();
			String[] newPic = gson.fromJson(parceImageInfo.get("url"), Pic.class).getPic();
			Pic picbean = new Pic();
			picbean.setPic(ArrayUtils.addAll(pic, newPic));
			posts.setPostsPics(gson.toJson(picbean));

			Size[] picSize = gson.fromJson(posts.getPostsPicsSize(), Size[].class);
			Size[] sizeJson = gson.fromJson(parceImageInfo.get("size"), Size[].class);
			Size[] addAll = ArrayUtils.addAll(picSize, sizeJson);
			posts.setPostsPicsSize(gson.toJson(addAll));

			String postsPicsDesc = posts.getPostsPicsDesc();
			Desc[] picDesc = null;
			int length = pic.length;
			if (null == postsPicsDesc || postsPicsDesc.equals("")) {
				picDesc = new Desc[length];
				for (int i = 0; i < length; i++) {
					Desc desc = new Desc();
					desc.setDesc("");
					picDesc[i] = desc;
				}
			} else {
				picDesc = gson.fromJson(postsPicsDesc, Desc[].class);
			}
			Desc[] newDesc = new Desc[picdesc.size()];
			for (int i = 0; i < picdesc.size(); i++) {
				Desc desc = new Desc();
				desc.setDesc(picdesc.get(i));
				newDesc[i] = desc;
			}
			Desc[] all = ArrayUtils.addAll(picDesc, newDesc);
			posts.setPostsPicsDesc(gson.toJson(all));
		}
		posts.setPostsSubject(addFriendPostsBean.getPostsSubject());
		posts.setPostUserId("15454d21023112m");
		posts.setPostsType(PostType.POST_TYPE_FRIEND);
		int insert = postsService.updateByPrimaryKeySelective(posts);
		if (insert > 0) {
			PostsFriend friend = postsFriendService.selectByPostsId(postsId);
			friend.setPostsAssembleTime(addFriendPostsBean.getPostsAssembleTime());
			friend.setPostsDestination(addFriendPostsBean.getPostsDestination());
			friend.setPostsPhone(addFriendPostsBean.getPostsPhone());
			friend.setPostsPopulation(addFriendPostsBean.getPostsPopulation());
			friend.setPostsRendezvous(addFriendPostsBean.getPostsRendezvous());
			postsFriendService.updateByPrimaryKeySelective(friend);
		}
		return "redirect:/posts/getPostsFriend";
	}


	/**
	 * 发布交易贴
	 * 
	 * @param addTradePostsBean
	 * @param post_pic
	 * @param picdesc
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addTradePosts", method = RequestMethod.POST)
	public String addTradePosts(AddTradePostsBean addTradePostsBean,
			@RequestParam MultipartFile[] post_pic, @RequestParam List<String> picdesc,
			HttpServletRequest request) {
		String postsId = CreateID.generate();

		/**
		 * 图片上传
		 */
		Map<String, String> parceImageInfo  = null;
		if(post_pic.length>0){
			List<ImageFileBean> imageList = uploadFiles(post_pic, postsId);
			parceImageInfo = parceImageInfo(imageList);
		}
		Posts posts = new Posts();
		posts.setPostsArea(addTradePostsBean.getPostsArea());
		posts.setPostsComment(0l);
		posts.setPostsContent(addTradePostsBean.getPostsContent());
		posts.setPostsCreatetime(DateUtils.dateToUnixTimestamp());
		posts.setPostsUpdateTime(DateUtils.dateToUnixTimestamp());
		posts.setPostsId(postsId);
		posts.setPostsLike(0l);
		if(null != parceImageInfo){
			posts.setPostsPics(parceImageInfo.get("url"));
			posts.setPostsPicsSize(parceImageInfo.get("size"));
		
			Desc[] descArray = new Desc[picdesc.size()];
			for (int i = 0; i < picdesc.size(); i++) {
				Desc desc = new Desc();
				desc.setDesc(picdesc.get(i));
				descArray[i] = desc;
			}
	
			GsonBuilder gsonBuilder = new GsonBuilder();
			Gson gson = gsonBuilder.create();
			posts.setPostsPicsDesc(gson.toJson(descArray));
		}
		posts.setPostsRead(0l);
		posts.setPostsSubject(addTradePostsBean.getPostsSubject());
		posts.setPostUserId("15454d21023112m");
		posts.setPostsType(PostType.POST_TYPE_TRADE);
		int insert = postsService.insert(posts);
		if (insert > 0) {
			PostsTrade trade = new PostsTrade();
			trade.setPId(CreateID.generate());
			trade.setPostsId(postsId);
			trade.setPostsMotoCost(addTradePostsBean.getPostsMotoCost());
			trade.setPostsMotoKilometer(addTradePostsBean.getPostsMotoKilometer());
			trade.setPostsMotoModel(addTradePostsBean.getPostsMotoModel());
			trade.setPostsMotoPhone(addTradePostsBean.getPostsMotoPhone());
			trade.setPostsMotoQuality(addTradePostsBean.getPostsMotoQuality());
			trade.setPostsMotoTime(addTradePostsBean.getPostsMotoTime());
			trade.setPostsTradeName(addTradePostsBean.getPostsTradeName());
			trade.setPostsTradeType(addTradePostsBean.getPostsTradeType());

			postsTradeService.insert(trade);
		}
		return "redirect:/posts/getPostsTrade";
	}

	/**
	 * 更新交易贴
	 * 
	 * @param addTradePostsBean
	 * @param post_pic
	 * @param picdesc
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateTradePosts", method = RequestMethod.POST)
	public String updateTradePosts(AddTradePostsBean addTradePostsBean, String postsId,
			@RequestParam MultipartFile[] post_pic, @RequestParam List<String> picdesc,
			HttpServletRequest request) {
		/**
		 * 图片上传
		 */
		Map<String, String> parceImageInfo = null;
		if (post_pic.length > 0) {
			List<ImageFileBean> imageList = uploadFiles(post_pic, postsId);
			parceImageInfo = parceImageInfo(imageList);
		}
		Posts posts = postsService.getPostsById(postsId);
		posts.setPostsArea(addTradePostsBean.getPostsArea());
		posts.setPostsContent(addTradePostsBean.getPostsContent());
		posts.setPostsUpdateTime(DateUtils.dateToUnixTimestamp());
		if (post_pic.length > 0) {
			GsonBuilder gsonBuilder = new GsonBuilder();
			Gson gson = gsonBuilder.create();

			String[] pic = gson.fromJson(posts.getPostsPics(), Pic.class).getPic();
			String[] newPic = gson.fromJson(parceImageInfo.get("url"), Pic.class).getPic();
			Pic picbean = new Pic();
			picbean.setPic(ArrayUtils.addAll(pic, newPic));
			posts.setPostsPics(gson.toJson(picbean));

			Size[] picSize = gson.fromJson(posts.getPostsPicsSize(), Size[].class);
			Size[] sizeJson = gson.fromJson(parceImageInfo.get("size"), Size[].class);
			Size[] addAll = ArrayUtils.addAll(picSize, sizeJson);
			posts.setPostsPicsSize(gson.toJson(addAll));

			String postsPicsDesc = posts.getPostsPicsDesc();
			Desc[] picDesc = null;
			int length = pic.length;
			if (null == postsPicsDesc || postsPicsDesc.equals("")) {
				picDesc = new Desc[length];
				for (int i = 0; i < length; i++) {
					Desc desc = new Desc();
					desc.setDesc("");
					picDesc[i] = desc;
				}
			} else {
				picDesc = gson.fromJson(postsPicsDesc, Desc[].class);
			}
			Desc[] newDesc = new Desc[picdesc.size()];
			for (int i = 0; i < picdesc.size(); i++) {
				Desc desc = new Desc();
				desc.setDesc(picdesc.get(i));
				newDesc[i] = desc;
			}
			Desc[] all = ArrayUtils.addAll(picDesc, newDesc);
			posts.setPostsPicsDesc(gson.toJson(all));
		}
		posts.setPostsSubject(addTradePostsBean.getPostsSubject());
		posts.setPostUserId("15454d21023112m");
		posts.setPostsType(PostType.POST_TYPE_TRADE);
		int insert = postsService.updateByPrimaryKeySelective(posts);
		if (insert > 0) {
			PostsTrade trade = postsTradeService.selectByPostsId(postsId);
			trade.setPostsMotoCost(addTradePostsBean.getPostsMotoCost());
			trade.setPostsMotoKilometer(addTradePostsBean.getPostsMotoKilometer());
			trade.setPostsMotoModel(addTradePostsBean.getPostsMotoModel());
			trade.setPostsMotoPhone(addTradePostsBean.getPostsMotoPhone());
			trade.setPostsMotoQuality(addTradePostsBean.getPostsMotoQuality());
			trade.setPostsMotoTime(addTradePostsBean.getPostsMotoTime());
			trade.setPostsTradeName(addTradePostsBean.getPostsTradeName());
			trade.setPostsTradeType(addTradePostsBean.getPostsTradeType());

			postsTradeService.updateByPrimaryKeySelective(trade);
		}
		return "redirect:/posts/getPostsTrade";
	}

	/**
	 * 解析图片信息
	 * 
	 * @param imageFileBeanList
	 * @return
	 */
	public static Map<String, String> parceImageInfo(List<ImageFileBean> imageFileBeanList) {
		List<ImageInfoBean> infoList = Lists.newArrayList();

		Bean bean = new Bean();
		String pic[] = new String[imageFileBeanList.size()];

		for (int i = 0; i < imageFileBeanList.size(); i++) {
			pic[i] = imageFileBeanList.get(i).getUrlBean().getUrl() + "-motostyle";
			infoList.add(imageFileBeanList.get(i).getImageInfoBean());
		}
		bean.setPic(pic);
		Gson gson = new Gson();

		String url = gson.toJson(bean);
		String size = gson.toJson(infoList);

		Map<String, String> map = Maps.newHashMapWithExpectedSize(2);

		map.put("url", url);
		map.put("size", size);
		return map;
	}

	/**
	 * 图片上传
	 * 
	 * @param post_pic
	 * @param postsId
	 * @return
	 */
	private List<ImageFileBean> uploadFiles(MultipartFile[] post_pic, String postsId) {
		/**
		 * 处理图片上传
		 */
		List<ImageFileBean> imageList = Lists.newArrayList();
		// 如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解
		// 并且上传多个文件时，前台表单中的所有<input type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件
		for (MultipartFile multipartFile : post_pic) {
			if (multipartFile.isEmpty()) {
				LOG.debug("后台发布【发现贴】 文件未上传");
			} else {
				String type = multipartFile.getContentType();
				String fileType = type.substring(type.indexOf("/") + 1, type.length());
				String fileName = postsId + "_" + DateUtils.dateToUnixTimestamp() + "." + fileType;
				// String realPath = "/opt/tomcat/tomcat-moto/upload/" + fileName;
				String realPath = "D:/upload/" + fileName;
				try {
					FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),
							new File(realPath));
					File file = new File(realPath);
					ImageFileBean imageFileBean = new ImageFileBean();
					ImageInfo imageInfo = Imaging.getImageInfo(file);
					ImageInfoBean imageInfoBean = new ImageInfoBean();
					imageInfoBean.setHeight(imageInfo.getHeight());
					imageInfoBean.setWidth(imageInfo.getWidth());
					imageFileBean.setImageInfoBean(imageInfoBean);

					String url = QiNiuFileUpload.upload(realPath, fileName);
					imageFileBean.setUrlBean(new ImageUrlBean(url));
					imageList.add(imageFileBean);
					// 上传完成，删除图片
				} catch (IOException e) {
					LOG.debug("异常");
				} catch (ImageReadException e) {
					// e.printStackTrace();
				}
			}
		}
		return imageList;
	}

	/**
	 * 删除帖子
	 * 
	 * @param postsId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String delete(@RequestParam("postsId") String postsId) {
		String flag = Boolean.TRUE.toString();
		/**
		 * 删除帖子
		 */
		Posts posts = postsService.getPostsById(postsId);
		/**
		 * 组队贴
		 */
		if (posts.getPostsType() == PostType.POST_TYPE_FRIEND) {

			postsFriendService.deleteByPostsId(postsId);
			postsFriendApplyService.deleteByPostsId(postsId);
		}
		/**
		 * 交易贴
		 */
		if (posts.getPostsType() == PostType.POST_TYPE_TRADE) {
			postsTradeService.deleteByPostsId(postsId);
		}

		/**
		 * 删除评论
		 */
		postsCommentService.deleteByPostsId(postsId);

		/**
		 * 删除提醒
		 */
		userRemindService.deleteByPostsId(postsId);

		/**
		 * 删除回复
		 */
		userRepliesService.deleteByPostsId(postsId);

		/**
		 * 删除收藏
		 */
		userStoreService.deleteByPostsId(postsId);
		/**
		 * 删除主题
		 */
		userSubjectService.deleteByPostsId(postsId);
		/**
		 * 删除帖子
		 */
		int delete = postsService.deleteByPrimaryKey(postsId);
		if (delete > 0) {
			flag = Boolean.TRUE.toString();
		} else {
			flag = Boolean.FALSE.toString();
		}

		return flag;
	}

	/**
	 * 查询帖子信息
	 * 
	 * @param postsId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public Map<String, Object> getPostsInfo(@RequestParam("postsId") String postsId) {
		Map<String, Object> result = Maps.newHashMap();

		LOG.info("查詢帖子詳情，帖子id=" + postsId);
		Posts posts = postsService.getPostsById(postsId);
		switch (posts.getPostsType()) {
			case PostType.POST_TYPE_DISCOVER:
				result.put("posts", posts);
				break;
			case PostType.POST_TYPE_FRIEND:
				PostsFriendBean friendBean = bulidingFriendPosts(posts);
				result.put("posts", friendBean);
				break;
			case PostType.POST_TYPE_PIC:
				result.put("posts", posts);
				break;
			case PostType.POST_TYPE_TRADE:
				PostsTradeBean tradeBean = bulidingTradePosts(posts);
				result.put("posts", tradeBean);
				break;
		}
		return result;
	}

	private PostsTradeBean bulidingTradePosts(Posts posts) {
		PostsTradeBean postsTradeBean = new PostsTradeBean();
		postsTradeBean.setPostsArea(posts.getPostsArea());
		if (null == posts.getPostsComment()) {
			postsTradeBean.setPostsComment(0l);
		} else {
			postsTradeBean.setPostsComment(posts.getPostsComment());
		}
		if (null == posts.getPostsContent()) {
			postsTradeBean.setPostsContent(NULL);
		} else {
			postsTradeBean.setPostsContent(posts.getPostsContent());
		}
		if (null == posts.getPostsPics()) {
			postsTradeBean.setPostsPics(NULL);
		} else {
			postsTradeBean.setPostsPics(posts.getPostsPics());
		}
		if (null == posts.getPostsPicsDesc()) {
			postsTradeBean.setPostsPicsDesc(NULL);
		} else {
			postsTradeBean.setPostsPicsDesc(posts.getPostsPicsDesc());
		}
		if (null == posts.getPostsPicsSize()) {
			postsTradeBean.setPostsPicsSize(NULL);
		} else {
			postsTradeBean.setPostsPicsSize(posts.getPostsPicsSize());
		}
		if (null == posts.getPostsSubject()) {
			postsTradeBean.setPostsSubject(NULL);
		} else {
			postsTradeBean.setPostsSubject(posts.getPostsSubject());
		}
		postsTradeBean.setPostsCreatetime(posts.getPostsCreatetime());
		postsTradeBean.setPostsId(posts.getPostsId());
		postsTradeBean.setPostsIsElite(posts.getPostsIsElite());
		postsTradeBean.setPostsLike(posts.getPostsLike());
		postsTradeBean.setPostsRead(posts.getPostsRead());
		postsTradeBean.setPostsType(posts.getPostsType());
		postsTradeBean.setPostsUpdateTime(posts.getPostsUpdateTime());
		postsTradeBean.setPostsUser(motoUserService.getUser(posts.getPostUserId()));

		PostsTrade postsTrade = postsTradeService.selectByPostsId(posts.getPostsId());
		if (null == postsTrade.getPostsTradeName()) {
			postsTradeBean.setPostsTradeName(NULL);
		} else {
			postsTradeBean.setPostsTradeName(postsTrade.getPostsTradeName());
		}
		if (null == postsTrade.getPostsMotoCost()) {
			postsTradeBean.setPostsMotoCost(NULL);
		} else {
			postsTradeBean.setPostsMotoCost(postsTrade.getPostsMotoCost());
		}
		if (null == postsTrade.getPostsMotoKilometer()) {
			postsTradeBean.setPostsMotoKilometer(NULL);
		} else {
			postsTradeBean.setPostsMotoKilometer(postsTrade.getPostsMotoKilometer());
		}
		if (null == postsTrade.getPostsMotoModel()) {
			postsTradeBean.setPostsMotoModel(NULL);
		} else {
			postsTradeBean.setPostsMotoModel(postsTrade.getPostsMotoModel());
		}
		if (null == postsTrade.getPostsMotoPhone()) {
			postsTradeBean.setPostsMotoPhone(NULL);
		} else {
			postsTradeBean.setPostsMotoPhone(postsTrade.getPostsMotoPhone());
		}
		if (null == postsTrade.getPostsMotoQuality()) {
			postsTradeBean.setPostsMotoQuality(NULL);
		} else {
			postsTradeBean.setPostsMotoQuality(postsTrade.getPostsMotoQuality());
		}
		if (null == postsTrade.getPostsMotoTime()) {
			postsTradeBean.setPostsMotoTime(NULL);
		} else {
			postsTradeBean.setPostsMotoTime(postsTrade.getPostsMotoTime());
		}
		if (null == postsTrade.getPostsTradeType()) {
			postsTradeBean.setPostsTradeType(NULL);
		} else {
			postsTradeBean.setPostsTradeType(postsTrade.getPostsTradeType());
		}
		return postsTradeBean;
	}

	private PostsFriendBean bulidingFriendPosts(Posts posts) {
		PostsFriendBean bean = new PostsFriendBean();
		bean.setPostsArea(posts.getPostsArea());
		if (null == posts.getPostsComment()) {
			bean.setPostsComment(0l);
		} else {
			bean.setPostsComment(posts.getPostsComment());
		}
		if (null == posts.getPostsContent()) {
			bean.setPostsContent(NULL);
		} else {
			bean.setPostsContent(posts.getPostsContent());
		}
		if (null == posts.getPostsPics()) {
			bean.setPostsPics(NULL);
		} else {
			bean.setPostsPics(posts.getPostsPics());
		}
		if (null == posts.getPostsPicsDesc()) {
			bean.setPostsPicsDesc(NULL);
		} else {
			bean.setPostsPicsDesc(posts.getPostsPicsDesc());
		}
		if (null == posts.getPostsPicsSize()) {
			bean.setPostsPicsSize(NULL);
		} else {
			bean.setPostsPicsSize(posts.getPostsPicsSize());
		}
		if (null == posts.getPostsSubject()) {
			bean.setPostsSubject(NULL);
		} else {
			bean.setPostsSubject(posts.getPostsSubject());
		}
		bean.setPostsCreatetime(posts.getPostsCreatetime());
		bean.setPostsId(posts.getPostsId());
		bean.setPostsIsElite(posts.getPostsIsElite());
		bean.setPostsLike(posts.getPostsLike());
		bean.setPostsRead(posts.getPostsRead());
		bean.setPostsType(posts.getPostsType());
		bean.setPostsUpdateTime(posts.getPostsUpdateTime());
		bean.setPostsUser(motoUserService.getUser(posts.getPostUserId()));

		PostsFriend postsFriend = postsFriendService.selectByPostsId(posts.getPostsId());

		if (null == postsFriend.getPostsAssembleTime()) {
			bean.setPostsAssembleTime(NULL);
		} else {
			bean.setPostsAssembleTime(postsFriend.getPostsAssembleTime());
		}

		if (null == postsFriend.getPostsDestination()) {
			bean.setPostsDestination(NULL);
		} else {
			bean.setPostsDestination(postsFriend.getPostsDestination());
		}

		if (null == postsFriend.getPostsPhone()) {
			bean.setPostsPhone(NULL);
		} else {
			bean.setPostsPhone(postsFriend.getPostsPhone());
		}

		if (null == postsFriend.getPostsPopulation()) {
			bean.setPostsPopulation(0l);
		} else {
			bean.setPostsPopulation(postsFriend.getPostsPopulation());
		}

		if (null == postsFriend.getPostsRendezvous()) {
			bean.setPostsRendezvous(NULL);
		} else {
			bean.setPostsRendezvous(postsFriend.getPostsRendezvous());
		}
		return bean;
	}

	@ResponseBody
	@RequestMapping(value = "/deleteImg", method = RequestMethod.GET)
	public String deleteImg(@RequestParam("imgName") String imgName,
			@RequestParam("postsId") String postsId, @RequestParam("index") Integer index) {
		Posts posts = postsService.getPostsById(postsId);

		String postsPics = posts.getPostsPics();
		String postsPicsDesc = posts.getPostsPicsDesc();
		String postsPicsSize = posts.getPostsPicsSize();


		GsonBuilder gsonBuilder = new GsonBuilder();
		Gson gson = gsonBuilder.create();

		String[] pic = gson.fromJson(postsPics, Pic.class).getPic();
		String[] removedPic = ArrayUtils.remove(pic, index);
		Pic picbean = new Pic();
		picbean.setPic(removedPic);
		String newPic = gson.toJson(picbean);

		Size[] picSize = gson.fromJson(postsPicsSize, Size[].class);
		Size[] removedPicSize = ArrayUtils.remove(picSize, index);
		String newPicSize = gson.toJson(removedPicSize);
		String newPicDesc = "[]";
		if (null == postsPicsSize || postsPicsSize.equals("")) {
			Desc[] picDesc = gson.fromJson(postsPicsDesc, Desc[].class);
			Desc[] removedPicDesc = ArrayUtils.remove(picDesc, index);
			newPicDesc = gson.toJson(removedPicDesc);
		}

		int updatePosts = postsService.updatePosts(postsId, newPic, newPicDesc, newPicSize);
		if (updatePosts > 0) {
			return Boolean.TRUE.toString();
		} else {
			return Boolean.FALSE.toString();
		}
	}
}


